package com.cms.bs.util;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import freemarker.template.TemplateExceptionHandler;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.core.io.Resource;

import java.io.*;
import java.util.Map;

public class FreemarkerUtil {

    private static Configuration config = null;

    /**
     * 构建 freemarker 配置
     * @param directory
     * @return
     */
    public static boolean buildConfiguration(String directory) {
        if (config == null) {
            config = new Configuration(Configuration.VERSION_2_3_23);
        }
        // 设置模板文件目录
        String templatePath = "classpath:/template/" + directory;
        try {
            Resource path = new DefaultResourceLoader().getResource(templatePath);
            config.setDirectoryForTemplateLoading(path.getFile());
            config.setDefaultEncoding("utf-8");
            config.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    /**
     * 处理 模板 与 数据
     * @param data
     * @param templateName
     * @param outputPath
     * @param outputName
     * @return
     */
    public static boolean process(Map<String, Object> data, String templateName, String outputPath, String outputName) {
        boolean success = false;
        Writer out = null;
        try {
            // 获取模板（template）
            Template template = config.getTemplate(templateName);

            File dir = new File(outputPath);
            if (!dir.exists()) {
                dir.mkdirs();
            }
            File outputFile = new File(dir, outputName);

            // 获取输出流
            out = new OutputStreamWriter(new FileOutputStream(outputFile));

            // 数据与模板合并（数据+模板=输出）
            template.process(data, out);
            out.flush();

            success = true;
        } catch (IOException e) {
            e.printStackTrace();
        } catch (TemplateException e) {
            e.printStackTrace();
        } finally {
            try {
                if (out != null) {
                    out.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return success;
    }
}